package com.test.view2img;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebView.PictureListener;
import android.widget.ImageView;

public class WebView2Img extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wv2i);
		final File cacheDir = getCacheDir();
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					ZipInputStream zis = new ZipInputStream(getResources()
							.openRawResource(R.raw.page1));
					ZipEntry ze = null;
					while ((ze = zis.getNextEntry()) != null) {
						FileOutputStream fos = new FileOutputStream(new File(
								cacheDir, ze.getName()));
						IOUtils.copy(zis, fos);
						IOUtils.closeQuietly(fos);
					}
					IOUtils.closeQuietly(zis);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				return true;
			}

			protected void onPostExecute(Boolean bool) {
				final WebView wv = (WebView) findViewById(R.id.webview);

				wv.setVisibility(View.INVISIBLE);
				wv.loadUrl(Uri.fromFile(cacheDir).toString() + "/index.html");
				wv.setPictureListener(new PictureListener() {

					@Override
					public void onNewPicture(WebView webview, Picture picture) {
						Picture pic = webview.capturePicture();
						Bitmap bmp = Bitmap.createBitmap(pic.getWidth(), pic
								.getHeight(), Config.RGB_565);
						Canvas cv = new Canvas(bmp);
						cv.drawPicture(pic);

						ImageView imgV = (ImageView) findViewById(R.id.img);
						imgV.setImageBitmap(bmp);
						findViewById(R.id.wait).setVisibility(View.INVISIBLE);
					}
				});
			};
		}.execute();

	}

}
